import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getCookie } from '@/utils/auth'
import router from '../router'

// create an axios instance
const axiosInstance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
axiosInstance.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['Authorization'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getCookie('adminToken')
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
axiosInstance.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 403) {
        router.push('/login')
      }
      if (res.code === 50012 || res.code === 50014 || res.code === 50011) {
        MessageBox.confirm(res.msg, '账号异常', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, err => {
          console.log(err)
        })
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 2000
        })
      }
      return Promise.reject(res)
    } else {
      if (res.message) {
        Message({
          type: 'success',
          message: res.message,
          duration: 1000
        })
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message || '服务异常',
      type: 'error',
      duration: 1000
    })
    return Promise.reject(error)
  }
)

export default axiosInstance
